<?php
/**
 *
 */
namespace Addons\ThreeWords\Model;

use Think\Model;

/**
 * Class ThreeWordsModel  三字评论词库模型
 * @package Addons\ThreeWords\Model
 * @author:xjw129xjt xjt@ourstu.com
 */
class ThreeWordsModel extends Model
{
    protected $tableName = 'three_words';
    protected $_auto = array(
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('update_time', NOW_TIME, self::MODEL_BOTH),
        array('status', '1', self::MODEL_INSERT),
    );

    protected $insertFields = 'title,color,used';
    protected $updateFields = 'title,color,used';

    public function addWords($data)
    {

        $data['color'] = $this->rgbToHex($data['color']);

        if (empty($data['title'])) {
            return false;
        }
        $res = $this->getWordMap($data);
        if ($res) {
            return $res['id'];
        }
        $data = $this->create($data);
        $res = $this->add($data);
        return $res;
    }

    public function getAllWords()
    {
        $words = $this->where(array('status' => 1,'is_default'=>1))->order('used desc,id asc')->select();
        return $words;
    }

    public function getWord($id)
    {
        $word = $this->where(array('id' => $id, 'status' => 1))->find();
        return $word;
    }

    public function getWordMap($map)
    {
        $map['status'] = 1;
        $word = $this->where($map)->find();
        return $word;
    }

    /**
     * rgbToHex RGB格式转换为十六进制
     * @param $rgb
     * @return string
     * @author:xjw129xjt xjt@ourstu.com
     */
    public function rgbToHex($rgb)
    {
        $regexp = "/^rgb\(([0-9]{0,3})\,\s*([0-9]{0,3})\,\s*([0-9]{0,3})\)/";
        $re = preg_match($regexp, $rgb, $match);
        if (!$match) {
            return $rgb;
        }
        $re = array_shift($match);
        $hexColor = "#";
        $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
        for ($i = 0; $i < 3; $i++) {
            $r = null;
            $c = $match[$i];
            $hexAr = array();

            while ($c > 16) {
                $r = $c % 16;

                $c = ($c / 16) >> 0;
                array_push($hexAr, $hex[$r]);

            }
            array_push($hexAr, $hex[$c]);
            $ret = array_reverse($hexAr);
            $item = implode('', $ret);
            $item = str_pad($item, 2, '0', STR_PAD_LEFT);
            $hexColor .= $item;
        }

        return $hexColor;

    }
}